package com.wenjoying.user.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.WeightedResponseTimeRule;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Base64;

@Configuration
public class RestConfig {

    /**
     * resttemplate启用负载均衡
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 选用其他负载均衡策略
     * @return
     */
    @Bean
    public IRule iRule() {
        return new WeightedResponseTimeRule();
    }

    /**
     * restTemplate配置security
     * @return
     */
    @Bean
    public HttpHeaders securityHeader() {
        HttpHeaders headers = new HttpHeaders();
        String auth = "wenjoying:wenjoying";
        byte[] bt = Base64.getEncoder().encode(auth.getBytes(Charset.forName("UTF-8")));
        String authHeader = "Basic" + new String(bt);
        headers.set("Authorization", authHeader);
        return headers;
    }

    /**
     * feign配置security
     */
    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("wenjoying", "wenjoying");
    }

}
